package cvi.com.reader.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.orhanobut.hawk.Hawk;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import cvi.com.reader.R;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.bean.LoginBean;
import cvi.com.reader.bean.ScanCodeBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.UtilsOnclickListen;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by WP on 2020/7/17.
 * 登录界面
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.phone_icon)
    ImageView phoneIcon;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.password_icon)
    ImageView passwordIcon;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.ip_icon)
    ImageView ipIcon;
    /*  @BindView(R.id.ip)
      EditText ipEdit;*/
    @BindView(R.id.ip_rl)
    RelativeLayout ipRl;
    @BindView(R.id.login)
    TextView login;
    @BindView(R.id.set_ip)
    TextView setIp;
/*    @BindView(R.id.register_ll)
    LinearLayout registerLl;
    @BindView(R.id.forgot_password)
    LinearLayout forgotPassword;*/
 /*   @BindView(R.id.qr_code_ll)
    LinearLayout qrCodeLl;*/
    private boolean isSetIp = false;
    private MyReceiver myReceiver;
    //自动登录账户、密码、IP。
    private String ipStr = "";
    private String nameStr = "";
    private String pwdStr = "";
    private static final int REQUEST_SCAN = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        setIp.setOnClickListener(this);
        login.setOnClickListener(this);
      /*  registerLl.setOnClickListener(this);
        forgotPassword.setOnClickListener(this);*/
       /* qrCodeLl.setOnClickListener(this);
        qrCodeLl.setVisibility(View.GONE);*/
        ipRl.setVisibility(View.GONE);
        getClassInfo();
    }

    @Override
    protected void initData() {

      /*  if (Hawk.contains("ip")) {
            ipStr = Hawk.get("ip");
            ipEdit.setText(ipStr);
        }*/
        if (Hawk.contains("loginName")) {
            nameStr = Hawk.get("loginName");
            phone.setText(nameStr);
        }
        if (Hawk.contains("loginPassword")) {
            pwdStr = Hawk.get("loginPassword");
            password.setText(pwdStr);
        }

    }

    @Override
    protected void extrasDoSome(Bundle extras) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login:
                //登录
                if (UtilsOnclickListen.isFastClick()) {
                    Login();
                }
                break;
            case R.id.set_ip:
                //是否设置IP，否则用公网Ip
                isSetIp();
                break;
/*            case R.id.register_ll:
               *//* if (ipEdit.getText().toString().trim().isEmpty()) {
           /* case R.id.register_ll:
               *//* if (ipEdit.getText().toString().trim().isEmpty()) {
                    Toast.makeText(LoginActivity.this, "IP不能为空!", Toast.LENGTH_LONG).show();
                    return;
                }*//*
               *//* if (!ipCheck(ipEdit.getText().toString().trim())) {
                    Toast.makeText(LoginActivity.this, "输入的IP格式有误！", Toast.LENGTH_LONG).show();
                    return;
                }*//*
                //IP格式无误，保存至数据库
                //Hawk.put("ip", ipEdit.getText().toString().trim());
                if (UtilsOnclickListen.isFastClick()) {
                    jump(RegisterActivity.class);
                }
                break;
            case R.id.forgot_password:
              *//*  if (ipEdit.getText().toString().trim().isEmpty()) {
                    Toast.makeText(LoginActivity.this, "IP不能为空!", Toast.LENGTH_LONG).show();
                    return;
                }*//*
                *//*if (!ipCheck(ipEdit.getText().toString().trim())) {
                    Toast.makeText(LoginActivity.this, "输入的IP格式有误！", Toast.LENGTH_LONG).show();
                    return;
                }*//*
                //IP格式无误，保存至数据库
                //  Hawk.put("ip", ipEdit.getText().toString().trim());
                if (UtilsOnclickListen.isFastClick()) {
                    jump(ForgotPassWordActivity.class);
                }
                break;
            case R.id.qr_code_ll:
                if (UtilsOnclickListen.isFastClick()) {
                    jumpScanPage();
                }
                break;*/
        }

    }

    /**
     * 跳转到扫码页
     */
    private void jumpScanPage() {
        startActivityForResult(new Intent(LoginActivity.this, CaptureActivity.class), REQUEST_SCAN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SCAN && resultCode == RESULT_OK) {
            String sacanCode = data.getStringExtra("barCode");
            if (sacanCode.isEmpty()) {
                return;
            }
            JSONObject jsonStr = JSONObject.parseObject(sacanCode);
            try {
                ScanCodeBean scanCodeBean = JSONObject.toJavaObject(jsonStr, ScanCodeBean.class);
                if (!scanCodeBean.getServer_url().isEmpty()) {
                    //ipEdit.setText(scanCodeBean.getServer_url());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

           /* Log.d("rwrwef", data.getStringExtra("barCode"));
            Toast.makeText(LoginActivity.this, data.getStringExtra("barCode"), Toast.LENGTH_LONG).show();*/
        }
    }

    private void Login() {
        if (phone.getText().toString().trim().isEmpty()) {
            Toast.makeText(LoginActivity.this, "用户名不能为空!" +
                    "" +
                    "", Toast.LENGTH_LONG).show();
            return;
        }
        if (password.getText().toString().trim().isEmpty()) {
            Toast.makeText(LoginActivity.this, "密码不能为空!", Toast.LENGTH_LONG).show();
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("account", phone.getText().toString().trim());
        map.put("password", password.getText().toString().trim());
        Hawk.put("loginName", phone.getText().toString().trim());
        Hawk.put("loginPassword", password.getText().toString().trim());
        NetWorkManager.getInstance().getNetWorkApiService().login(map).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(LoginActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        LoginBean loginBean = response.toJavaObject(LoginBean.class);
                        LoginBean.DataBean.UserInfoBean msgBean = loginBean.getData().getUser_info();
                        Toast.makeText(LoginActivity.this, "登陆成功！", Toast.LENGTH_LONG).show();
                        Hawk.put("LoginBean", loginBean);
                        Hawk.put("token", loginBean.getData().getToken());
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();

                    }
                });
    }

    private void getClassInfo() {

        NetWorkManager.getInstance().getNetWorkApiService().getClassInfo().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(LoginActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {


                    }
                });
    }
    private void getClasslistInfo() {

        NetWorkManager.getInstance().getNetWorkApiService().getsLogin("203").compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(LoginActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {

                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                  Log.d("rgerter222",response.toString());
                    }
                });
    }


    private void isSetIp() {
        if (constant.DEFAULT_IP.equals(setIp.getText().toString().trim())) {
            setIp.setText(constant.CLICK_IP);
            //隐藏显示动画
            ipRl.animate()
                    .alpha(1f)
                    .setDuration(1000)
                    .setListener(null);
            ipRl.setVisibility(View.VISIBLE);
            isSetIp = true;
        } else if (constant.CLICK_IP.equals(setIp.getText().toString().trim())) {
            setIp.setText(constant.DEFAULT_IP);
            //隐藏显示动画
            ipRl.animate()
                    .alpha(0.8f)
                    .setDuration(1000)
                    .setListener(null);
            ipRl.setVisibility(View.GONE);
            isSetIp = false;
        }
    }

    public boolean isIP(String addr) {
        if (addr.length() < 7 || addr.length() > 15 || "".equals(addr)) {
            return false;
        }
        /**
          * 判断IP格式和范围
          */
        String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";

        Pattern pat = Pattern.compile(rexp);

        Matcher mat = pat.matcher(addr);

        boolean ipAddress = mat.find();

        //============对之前的ip判断的bug在进行判断
        if (ipAddress == true) {
            String ips[] = addr.split("\\.");

            if (ips.length == 4) {
                try {
                    for (String ip : ips) {
                        if (Integer.parseInt(ip) < 0 || Integer.parseInt(ip) > 255) {
                            return false;
                        }

                    }
                } catch (Exception e) {
                    return false;
                }

                return true;
            } else {
                return false;
            }
        }

        return ipAddress;
    }

    //含有端口的IP验证
    public boolean ipCheck(String text) {
        if (text != null && text.length() > 0) {
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\:\\d{1,5}$";
            Pattern ipAndPortPattern = Pattern.compile(regex);
            Matcher matcher = ipAndPortPattern.matcher(text);
            matcher.reset();
            if (!matcher.matches()) {
                return false;
            } else {
                return true;
            }
        }
        // 返回判断信息
        return false;
    }

    private void setChangeIp() {
        if (Hawk.contains("loginName")) {
            nameStr = Hawk.get("loginName");
        }
        if (Hawk.contains("loginPassword")) {
            pwdStr = Hawk.get("loginPassword");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("username", nameStr.trim());
        map.put("password", pwdStr.trim());
        NetWorkManager.getInstance().getNetWorkApiService().login(map).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(LoginActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        LoginBean loginBean = response.toJavaObject(LoginBean.class);
                        LoginBean.DataBean.UserInfoBean msgBean = loginBean.getData().getUser_info();
                        Hawk.put("LoginBean", loginBean);
                    }
                });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        //广播1
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(constant.CLOSElOGIN_MYRECEIVER);
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, intentFilter);

        //广播2
        IntentFilter intentFilter2 = new IntentFilter();
        intentFilter2.addAction(constant.CHANGE_IP);
        registerReceiver(myReceiver, intentFilter2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
        }
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (constant.CLOSElOGIN_MYRECEIVER.equals(intent.getAction())) {
                finish();
            } else if (constant.CHANGE_IP.equals(intent.getAction())) {
                setChangeIp();
            }

        }
    }
}

